<template>
    <el-row class="file-div" :gutter="20">
        <div v-if="Object.keys(stageList).length === 0" class="empty-message">
            请先选择您要查看的班级
        </div>
        <el-menu v-else default-active="2" class="file-list" @open="handleOpen" @close="handleClose">
            <el-sub-menu v-for="(item, index) in stageList" :key="index" :index="item.stage.toString()" class="item-with-icon">
                <template #title class="stageDiv">
                    第{{ item.stage }}阶段
                </template>

                <el-menu-item v-for="(node, index) in item.nodes" :key="node" :index="node.title + '-' + index">
                    <span class="node-title" @click="handleNodeId(node)">{{ node.title }}</span>
                    <div class="icon-child-group"></div>
                </el-menu-item>
            </el-sub-menu>
        </el-menu>
    </el-row>
</template>

<script lang="ts" setup>
import { onMounted, ref,computed  } from 'vue'
import { storeInfo } from '@/stores/storeinfo'
import { useEditorStore } from '@/stores/editStore'
import { useUserStore } from '@/stores/userStore'
import {nodeinfo} from '@/stores/nodeinfo'
import { currentNodeInfo } from '@/stores/currentNodeStore'
import {studentClass} from '@/stores/studentClass'
import { useCommentStore } from '@/stores/commentStore'
import { CommentPlugin } from '@/tiptap/extensions/CommentPlugin'
import { useCommentPluginStore } from '@/stores/commentPluginStore'
const editorStore = useEditorStore();
const studentClassStore = studentClass();
const storeinfo = storeInfo();
const currentNodeStore = currentNodeInfo()
const classId = computed(() => storeinfo.studentClassId)
console.log("获取到的classId", classId);
//获取userId
const userId = useUserStore().user.id;
console.log("获取userid",useUserStore().user.id);
const nodeinfoStore = nodeinfo();

let stageList = ref({})

onMounted(async () => {

     await studentClassStore.getStudentClassById(userId)

        const nodeQueryInfo = ref({
            classId: classId,
            userId: userId,
        })
        console.log("获取到的查询笔记的信息：", nodeQueryInfo.value)
        await nodeinfo().getNodeInfo(nodeQueryInfo.value)
        stageList.value = nodeinfo().stageList
;
})


const handleOpen = (key: string, keyPath: string[]) => {
    console.log(key, keyPath)
}

const handleClose = (key: string, keyPath: string[]) => {
    console.log(key, keyPath)
}


const handleNodeId = async (currentNode: any) => {

  // 1️⃣ 保存当前批注（若有更改）
  try {
    await useCommentStore().save()
    console.log('已自动保存当前批注')
  } catch (e) {
    console.warn('批注保存失败:', e)
  }
  
    storeinfo.setNowContent(currentNode.content)
    editorStore.getCurrentNode(currentNode.nodeId)
    await useCommentStore().load(currentNode.nodeId, userId)
    const commentPlugin = useCommentPluginStore().pluginInstance
    commentPlugin.loadComments?.(useCommentStore().commentList);
    console.log("渲染的批注", useCommentStore().commentList);
}


// 获取默认文件名（带序号）
const getDefaultFileName = (stageItem: any) => {
    let defaultName = '新建文件';
    let counter = 1;

    while (isFileNameDuplicate(stageItem, `${defaultName}${counter > 1 ? ` ${counter}` : ''}`)) {
        counter++;
    }

    return `${defaultName}${counter > 1 ? ` ${counter}` : ''}`;
}

// 检查文件名是否重复
const isFileNameDuplicate = (stageItem: any, fileName: string, excludeIndex?: number) => {
    if (!stageItem.nodes) return false;

    return stageItem.nodes.some((node: any, index: number) => {
        // 排除自身检查
        if (excludeIndex !== undefined && index === excludeIndex) return false;
        return node.title === fileName;
    });
}




</script>
<style scoped>
.input-title{
    display: flex;
    align-items: start;
}
.error-message {
    position: absolute;
    left: 0;
    bottom: 0px; /* 将错误信息定位在输入框下方 */
    color: #f56c6c;
    font-size:10px;
    line-height: 1;
    padding-top: 2px;
    display: flex;
    padding-left: 20%;
}

/* 当有错误时，调整输入框边框颜色 */
.is-error :deep(.el-input__wrapper) {
    box-shadow: 0 0 0 1px #f56c6c inset;
}
/* 子菜单项的图标控制 */
.icon-child-group {
    opacity: 0;
    transition: opacity 0.2s ease;
    display: flex;
    position: absolute;
    right: 20px;
}

/* 使用更精确的选择器确保生效 */
:deep(.el-menu-item):hover .icon-child-group,
.el-menu-item:hover .icon-child-group {
    opacity: 1;
}

/* 初始状态下隐藏图标 */
.item-with-icon .icon-group {
    opacity: 0;
    transition: opacity 0.3s ease;
}

/* 鼠标悬停时显示图标 */
.item-with-icon:hover .icon-group {
    opacity: 1;
}
:deep(.el-sub-menu .el-sub-menu__title) {
    background-color: #bfd6ee;
}

/* 修改菜单项高度 */
.file-list :deep(.el-menu-item),
.file-list :deep(.el-sub-menu__title) {
    height: 45px;
    /* 设置为你想要的高度 */
    line-height: 45px;
    /* 保持与高度一致以确保垂直居中 */
}

.icon-group {
    display: flex;
    gap: 0px;
    position: absolute;
    right: 30px;
}

.item-with-icon {
    position: relative;
}

.file-div {
    overflow: auto;
    text-align: center;
}

.file-list {
    width: 100%;
}

/* 菜单项文本自动换行 */
.el-menu-item span,
.el-sub-menu__title span {
    white-space: normal;
    word-break: break-word;
}
</style>
